package com.sicnu.cheer.leaugebar.leaguemodle.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sicnu.cheer.generalmodule.activity.BaseActivity;
import com.sicnu.cheer.generalmodule.adapter.base.CommonAdapter;
import com.sicnu.cheer.generalmodule.adapter.viewholder.CommonViewHolder;
import com.sicnu.cheer.generalmodule.bean.AlbumBean;
import com.sicnu.cheer.generalmodule.config.Constant;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.leaugebar.leaguemodle.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DeleteBatchListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadBatchListener;
import io.github.lijunguan.imgselector.ImageSelector;

/**
 * 照片宫格页
 */
public class PhotoActivity extends BaseActivity implements View.OnClickListener {

    private TextView titleTV;
    private AlbumBean bean;
    private LinearLayout noResultLL;
    private GridView photoGV;
    private CommonAdapter<String> mAdapter;
    private ProgressDialog progressDialog;
    private ArrayList<String> picUrls;
    private boolean uploadSuccess=true;


    private boolean isEditable = false;
    private ImageView rightIV;
    private ArrayList<String> deleteUrls = new ArrayList();//要删除的图片的url
    private ImageView mainBtn;

    @Override
    public int getContentViewId() {
        return R.layout.activity_photo;
    }

    @Override
    protected void initView() {
        super.initView();
        findViewById(R.id.back).setOnClickListener(this);
        mainBtn = ((ImageView) findViewById(R.id.add_pic_btn));
        mainBtn.setOnClickListener(this);
        rightIV = (ImageView) findViewById(R.id.title_right_button);
        rightIV.setImageResource(R.mipmap.album_edit);
        rightIV.setOnClickListener(this);
        titleTV = ((TextView) findViewById(R.id.title));

        noResultLL = ((LinearLayout) findViewById(R.id.no_data_ll));
        noResultLL.setVisibility(View.GONE);
        photoGV = ((GridView) findViewById(R.id.data_list));
    }

    @Override
    protected void initData() {
        super.initData();
        setResult(Constant.ALBUM_RESULT_FROM);
        picUrls=new ArrayList<>();
        bean = (AlbumBean) getIntent().getSerializableExtra("bean");
        progressDialog=new ProgressDialog(mThis);
        progressDialog.setMessage("加载中...");
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        photoGV.setAdapter(mAdapter = new CommonAdapter<String>(mThis,picUrls,R.layout.layout_single_img) {
            @Override
            public void convert(CommonViewHolder helper, String item) {
                helper.setImageByUrl(R.id.single_photo, item,R.mipmap.default_pic);
                helper.setMyVisibility(R.id.capture_delete,isEditable);
                helper.setSelectState(R.id.capture_delete,deleteUrls.contains(item));
            }
        });
        if (bean!=null) {
            titleTV.setText(bean.getName());
            if (bean.getImgUrls() != null && bean.getImgUrls().size() != 0) {
                picUrls.addAll(bean.getImgUrls());
                mAdapter.notifyDataSetChanged();
            }else {
                setNoResultState();
            }
        }
        photoGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isEditable) {
                    ImageView delete = (ImageView) view.findViewById(R.id.capture_delete);
                    delete.setSelected(!delete.isSelected());
                    if (delete.isSelected()) {
                        deleteUrls.add(picUrls.get(position));
                    } else {
                        if (deleteUrls.contains(picUrls.get(position))) {
                            deleteUrls.remove(picUrls.get(position));
                        }
                    }

                } else {
                    Intent intent=new Intent(mThis,BigPhotoActivity.class);
                    intent.putExtra("list",picUrls);
                    intent.putExtra("imgPosition",position);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.back){
            onBackPressed();
        }else if (v.getId()==R.id.title_right_button){
            editAlbum();
        }else if (v.getId()==R.id.add_pic_btn){
            if (isEditable){
                deleteUrls.clear();
                //设置全选.取消全选
                if (!mainBtn.isSelected()){
                    deleteUrls.addAll(picUrls);
                }
                mainBtn.setSelected(!mainBtn.isSelected());
                mAdapter.notifyDataSetChanged();
            }else {
                ImageSelector.getInstance()
                        .setSelectModel(ImageSelector.MULTI_MODE)
                        .setMaxCount(9)
                        .setGridColumns(4)
                        .setShowCamera(true)
                        .setToolbarColor(getResources().getColor(R.color.theme_green_color))
                        .startSelect(this);
            }
        }
    }

    /**
     * 编辑相册，可以实现选中后删除,
     * 如果是非编辑状态，则设置为编辑状态
     * 如果是编辑状态，则实现删除判断逻辑
     */
    private void editAlbum() {
        if (!isEditable) {
            setEditable();
        } else {
            deleteImg();
        }
    }
    /**
     * 编辑状态时，改变各个参数
     */
    private void setEditable() {
        isEditable = true;
        mAdapter.notifyDataSetChanged();
        rightIV.setImageResource(R.mipmap.album_delete);
        mainBtn.setImageResource(R.mipmap.check_all);
    }
    /**
     * 非编辑状态时，改变各个参数
     */
    private void setUnEditable() {
        isEditable = false;
        mAdapter.notifyDataSetChanged();
        rightIV.setImageResource(R.mipmap.album_edit);
        mainBtn.setImageResource(R.mipmap.add);
    }
    /**
     * 删除图片，判断是否删除完毕，删除完毕设置界面的空状态
     */
    private void deleteImg() {
        if (deleteUrls.size() != 0) {
            final String [] urls=new String[deleteUrls.size()];
            deleteUrls.toArray(urls);
            progressDialog.show();
            bean.getImgUrls().removeAll(deleteUrls);
            ArrayList<String> leftUrls=new ArrayList<String>();
            leftUrls.addAll(bean.getImgUrls());
            bean.setImgUrls(leftUrls);
            bean.update(mThis, bean.getObjectId(), new UpdateListener() {
                @Override
                public void onSuccess() {
                    BmobFile.deleteBatch(mThis, urls, new DeleteBatchListener() {
                        @Override
                        public void done(String[] strings, BmobException e) {
                            progressDialog.dismiss();
                            if(e==null){
                                UIHelper.ToastMessage(mThis, "删除成功");
                                picUrls.removeAll(deleteUrls);
                                deleteUrls.clear();
                                mAdapter.notifyDataSetChanged();
                            }else{
                                if(strings!=null){
                                    UIHelper.ToastMessage(mThis,"删除失败个数："+strings.length+","+e.toString());
                                }else{
                                    UIHelper.ToastMessage(mThis,"全部文件删除失败："+e.getErrorCode()+","+e.toString());
                                }
                            }

                        }
                    });
                }
                @Override
                public void onFailure(int i, String s) {
                    progressDialog.dismiss();
                    UIHelper.ToastMessage(mThis,"删除失败");
                }
            });

            if (picUrls.isEmpty()) {
                setNoResultState();
            }
        } else {
            UIHelper.ToastMessage(mThis,"请选择想要删除的图片");
        }
    }

    private void setNoResultState() {
        rightIV.setVisibility(View.INVISIBLE);
        rightIV.setEnabled(false);
        noResultLL.setVisibility(View.VISIBLE);
    }

    /**
     * 从选择图片或者拍照返回，或者选择社团activity返回
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageSelector.REQUEST_SELECT_IMAGE
                && resultCode == RESULT_OK) {
            final ArrayList<String> imagesPath = data.getStringArrayListExtra(ImageSelector.SELECTED_RESULT);
            if (imagesPath != null) {
                progressDialog.show();
                //批量上传
                uploadSuccess=false;
                String[] strings = new String[imagesPath.size()];
                imagesPath.toArray(strings);
                BmobFile.uploadBatch(mThis,strings, new UploadBatchListener() {
                    @Override
                    public void onSuccess(List<BmobFile> files, List<String> urls) {
                        if(urls.size()==imagesPath.size()){//如果数量相等，则代表文件全部上传完成
                            updateAlbum(urls);
                        }
                    }

                    @Override
                    public void onError(int statuscode, String errormsg) {
                        progressDialog.dismiss();
                        UIHelper.ToastMessage(mThis,"错误描述："+errormsg);
                    }

                    @Override
                    public void onProgress(int curIndex, int curPercent, int total,int totalPercent) {
                        //1、curIndex--表示当前第几个文件正在上传
                        //2、curPercent--表示当前上传文件的进度值（百分比）
                        //3、total--表示总的上传文件数
                        //4、totalPercent--表示总的上传进度（百分比）
                    }
                });
            }
        }
    }

    private void updateAlbum(final List<String> urls) {
        bean.getImgUrls().addAll(urls);
        bean.update(mThis, new UpdateListener() {
            @Override
            public void onSuccess() {
                afterSuccess(urls);
            }

            @Override
            public void onFailure(int i, String s) {
                progressDialog.dismiss();
                UIHelper.ToastMessage(mThis,"图片上传失败："+s);
            }
        });
    }

    private void afterSuccess(List<String> urls) {
        photoGV.setVisibility(View.VISIBLE);
        noResultLL.setVisibility(View.GONE);
        uploadSuccess=true;
        progressDialog.dismiss();
        picUrls.addAll(urls);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        if (uploadSuccess){
            if (deleteUrls.isEmpty()){
                if (isEditable && rightIV.isEnabled()) {
                    setUnEditable();
                } else {
                    super.onBackPressed();
                }
            }else {
                deleteUrls.clear();
                mAdapter.notifyDataSetChanged();
            }
        }else {
            exitBy2Click();
        }
    }
    /**
     * 双击退出函数
     *  
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次取消上传", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            super.onBackPressed();
        }
    }
}
